package com.phpxiu.app.view;

import android.content.Intent;
import android.graphics.drawable.AnimationDrawable;
import android.hardware.Camera;
import android.os.Build;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.ActivityCompat;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.view.KeyEvent;
import android.view.View;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.phpxiu.app.api.OnDialogClickListener;
import com.phpxiu.app.api.callback.EnterRoomChecker;
import com.phpxiu.app.api.callback.MsgCountManager;
import com.phpxiu.app.config.Constants;
import com.phpxiu.app.config.HttpConfig;
import com.phpxiu.app.controller.avcontroller.QavsdkControl;
import com.phpxiu.app.kkylive.KKYApp;
import com.phpxiu.app.kkylive.R;
import com.phpxiu.app.model.CurLiveInfo;
import com.phpxiu.app.model.MySelfInfo;
import com.phpxiu.app.model.Permission;
import com.phpxiu.app.model.event.OnForceLogoutEvent;
import com.phpxiu.app.model.event.OnLanguageEvent;
import com.phpxiu.app.model.gift.Gift;
import com.phpxiu.app.model.response.AuthenticationModel;
import com.phpxiu.app.model.response.GiftListModel;
import com.phpxiu.app.model.response.SystemDefaultMsg;
import com.phpxiu.app.model.response.SystemMsgModel;
import com.phpxiu.app.okhttp.OKHttp;
import com.phpxiu.app.okhttp.handler.OKHttpUIHandler;
import com.phpxiu.app.okhttp.param.OKHttpParam;
import com.phpxiu.app.utils.KKYUtil;
import com.phpxiu.app.view.custom.WindowLayout;
import com.phpxiu.app.view.fragment.BaseFragment;
import com.phpxiu.app.view.fragment.HomeFragment;
import com.phpxiu.app.view.fragment.UserFragment;
import com.tencent.TIMManager;
import com.tencent.TIMUserStatusListener;

import java.util.ArrayList;
import java.util.List;

import de.greenrobot.event.EventBus;
import de.greenrobot.event.Subscribe;


/**
 * Created by WuJinZhou on 2016/4/26.
 */
public class Main extends UIBase implements View.OnClickListener,ActivityCompat.OnRequestPermissionsResultCallback,TIMUserStatusListener {
    public final static String TAG="Main";
    public final static String CHECK="check";

    public final static int REQUEST_CODE_AUTHENTICATION=0x67;//前往认证

    public final static List<SystemDefaultMsg>SYSTEM_MSG=new ArrayList<SystemDefaultMsg>();
    private WindowLayout mainView;
    private FragmentManager manager;
    private FragmentTransaction transaction;
    private BaseFragment liveFrag,userFrag;
    private RelativeLayout indexMenu,userMenu;
    private TextView indexMenuTitle,userMenuTitle;
    private ImageView indexMenuIcon,userMenuIcon;
    private ImageButton videoMenu;
    private View checkCoverView;//检测开播时，显示的等待进度视图

    private AnimationDrawable checking;//检测等待动画

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        EventBus.getDefault().register(this);
        if(QavsdkControl.getInstance().getAVContext()==null){
            EnterRoomChecker.getInstance().IMLogin(MySelfInfo.getInstance().getId(),MySelfInfo.getInstance().getUserSig());//重新登录
        }
        TIMManager.getInstance().setUserStatusListener(this);//登录监听
        TIMManager.getInstance().addMessageListener(MsgCountManager.getInstance());
        loadGiftsList();//加载礼物列表
        loadSystemMsg();//加载默认系统通知
        setContentView(R.layout.main);
        mainView=(WindowLayout)findViewById(R.id.main_view);
        init();
    }

    /**
     * 初始化
     */
    private void init(){
        manager=getSupportFragmentManager();
        indexMenu=(RelativeLayout)findViewById(R.id.live_model_menu);
        indexMenu.setOnClickListener(this);
        indexMenuIcon=(ImageView)findViewById(R.id.live_model_menu_icon);
        indexMenuTitle=(TextView)findViewById(R.id.live_model_menu_title);
        //indexMenuTitle.setText("\ud83d\udc96");
        indexMenuTitle.setSelected(true);
        checkCoverView=findViewById(R.id.check_state_cover_view);
        checking=(AnimationDrawable)findViewById(R.id.check_image_view).getBackground();
        videoMenu=(ImageButton)findViewById(R.id.go_live_model_menu);
        videoMenu.setOnClickListener(this);

        userMenu=(RelativeLayout)findViewById(R.id.user_model_menu);
        userMenu.setOnClickListener(this);
        userMenuIcon=(ImageView)findViewById(R.id.user_model_menu_icon);
        userMenuTitle=(TextView)findViewById(R.id.user_model_menu_title);
        indexMenu.performClick();
    }

    @Override
    public void onClick(View v) {
        if(v.getId()== R.id.live_model_menu||v.getId()== R.id.user_model_menu){
            transaction=manager.beginTransaction();
            hideFragments();
        }
        switch (v.getId()){
            case R.id.live_model_menu:
                OKHttp.cancelRequest(CHECK);
                checkComplete();
                if(liveFrag==null){
                    liveFrag= HomeFragment.builder(null);
                    transaction.add(R.id.home_mode_box,liveFrag);
                }else{
                    transaction.show(liveFrag);
                }
                userMenuTitle.setSelected(false);
                indexMenuTitle.setSelected(true);
                indexMenuIcon.setImageResource(R.mipmap.main_index_navigator_selected);
                userMenuIcon.setImageResource(R.mipmap.main_user_navigator_normal);
                break;
            case R.id.go_live_model_menu:
                if(Build.VERSION.SDK_INT>Build.VERSION_CODES.LOLLIPOP){
                    requestMyPermissions(Permission.REQUEST_COMMON);
                }else {
                    goCreateAVRoom();
                }
                break;
            case R.id.user_model_menu:
                OKHttp.cancelRequest(CHECK);
                checkComplete();
                if(userFrag==null){
                    userFrag= UserFragment.builder(null);
                    transaction.add(R.id.home_mode_box,userFrag);
                }else{
                    transaction.show(userFrag);
                }
                userFrag.onInit(this);
                userMenuTitle.setSelected(true);
                indexMenuTitle.setSelected(false);
                indexMenuIcon.setImageResource(R.mipmap.main_index_navigator_normal);
                userMenuIcon.setImageResource(R.mipmap.main_user_navigator_selected);
                break;
            default:
                break;
        }
        if(v.getId()== R.id.live_model_menu||v.getId()== R.id.user_model_menu){
            //transaction.commit();
            transaction.commitAllowingStateLoss();
        }
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        //两次按下间隔大于1秒小于3秒的时间(只有两次狂点无效)
        //返回键盘事件
        if(keyCode==KeyEvent.KEYCODE_BACK){
            interactiveDialog(getString(R.string.ui_exit_title),
                    getString(R.string.ui_exit_desc),getString(R.string.ui_exit),getString(R.string.dialog_cancel),
                    new OnDialogClickListener() {
                @Override
                public void onOk() {
                    finish();
                }

                @Override
                public void onCancel() {
                      //do nothing
                }
            });
        }
        return false;
    }


    /**
     * 被迫下线
     */
    @Override
    public void onForceOffline() {
        //强制下线，因账号在别的设备上已登录(未退出IM登录)
        forceExit(getString(R.string.login_force_out));
    }

    /**
     * IM登录过期
     */
    @Override
    public void onUserSigExpired() {
        forceExit(getString(R.string.login_expired));
    }

    /**
     * 强制登出
     */
    public void forceExit(String msg) {
        if(!CurLiveInfo.isInRoom){//不在直播中
            Intent loginOut = new Intent(this, ForceLoginOut.class);
            loginOut.putExtra(ForceLoginOut.REASON_MSG, msg);
            startActivity(loginOut);
        }else{
            EventBus.getDefault().post(new OnForceLogoutEvent());
        }
    }

    /**
     * 隐藏首页界面
     */
    private void hideFragments(){
        if(liveFrag!=null){
            transaction.hide(liveFrag);
        }
        if(userFrag!=null){
            transaction.hide(userFrag);
        }
    }

    @Override
    public void onResume() {
        super.onResume();
    }

    @Override
    public void finish(){
        TIMManager.getInstance().removeMessageListener(MsgCountManager.getInstance());
        super.finish();
    }

    @Override
    protected void onDestroy() {
        TIMManager.getInstance().removeMessageListener(MsgCountManager.getInstance());
        EventBus.getDefault().unregister(this);
        super.onDestroy();
    }

    /**
     * 检测认证状态
     */
    private void checkAuthentication(){
        String state=MySelfInfo.getInstance().getVerifyState();
        KKYUtil.log("认证状态："+state);
        if(false){
            Intent authentication=new Intent(Main.this,UserAuthentication.class);
            startActivityForResult(authentication,REQUEST_CODE_AUTHENTICATION);
            return;
        }
        if("2".equals(state)||"1".equals(state)){//实名认证审核已通过:2审核通过，1审核中
            goPublishLive();
            return;
        }
        if(checkCoverView!=null&&checkCoverView.getVisibility()!=View.VISIBLE){
            checkCoverView.setVisibility(View.VISIBLE);
        }
        if(checking!=null){
            checking.start();
        }
        OKHttpParam param=OKHttpParam.builder(false);
        OKHttp.post(HttpConfig.API_USER_CHECK_VERIFY,param.jsonParam(),CHECK,new OKHttpUIHandler(AuthenticationModel.class) {
            @Override
            public void onSuccess(Object model) {
                AuthenticationModel m=(AuthenticationModel)model;
                KKYUtil.log("检测后台认证状态："+m.getResponseStr());
                try {
                    MySelfInfo.getInstance().updateCacheString(Main.this,Constants.USER_VERIFY_STATE,m.getData().getApproved());
                    String newState=MySelfInfo.getInstance().getVerifyState();
                    if("1".equals(newState)){//实名认证审核中...
                        mainView.showTopMsg(getString(R.string.authentication_state_msg));
                    }
                    if("0".equals(newState)||"3".equals(newState)){
                        //实名认证没有提交材料或认证没有通过
                        Intent authentication=new Intent(Main.this,UserAuthentication.class);
                        startActivityForResult(authentication,REQUEST_CODE_AUTHENTICATION);
                    }
                }catch (Exception e){
                    e.printStackTrace();
                }
                checkComplete();
            }
            @Override
            public void onErr(String errMsg) {
                mainView.showTopMsg(errMsg);
                checkComplete();
            }
        });
    }

    /**
     * 检测结束
     */
    final private void checkComplete(){
        if(checkCoverView!=null&&checkCoverView.getVisibility()==View.VISIBLE){
            checkCoverView.setVisibility(View.INVISIBLE);
        }
        if(checking!=null){
            checking.stop();
        }
    }

    @Override
    protected void onPermission(int requestCode) {
        goCreateAVRoom();
    }

    /**
     * 检测开播
     */
    public void goCreateAVRoom(){
        if(checkCoverView.getVisibility()==View.VISIBLE){
            return;
        }
        boolean noCamera=false;
        Camera c=null;
        try{
           c=Camera.open();
        }catch (Exception e){
            mainView.showTopMsg(getString(R.string.camera_disable_msg));
            noCamera=true;
        }finally {
            try {
                if (c != null) {
                    c.release();
                }
            }catch (Exception e){

            }
        }
        if(noCamera){
            return;
        }
        //SDK实例存在
        if(QavsdkControl.getInstance().getAVContext()!=null){
            checkAuthentication();//是否认证
        }else{
            mainView.showTopMsg(getString(R.string.start_failed_msg));
            EnterRoomChecker.getInstance().IMLogin(MySelfInfo.getInstance().getId(),MySelfInfo.getInstance().getUserSig());//重新登录
        }
    }

    /**
     *可以发布，跳到发布界面
     */
    final private void goPublishLive(){
        Intent liveInit=new Intent(Main.this,PublishLive.class);
        startActivity(liveInit);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if(requestCode==REQUEST_CODE_AUTHENTICATION){
            if(resultCode==RESULT_OK){
                Intent liveInit=new Intent(Main.this,PublishLive.class);
                startActivity(liveInit);
            }
        }
    }

    /**
     * 加载礼物列表数据
     */
    private void loadGiftsList(){
        OKHttpParam param=OKHttpParam.builder();
        OKHttp.post(HttpConfig.API_GET_GIFT_LIST, param.jsonParam(), TAG, new OKHttpUIHandler(GiftListModel.class) {
            @Override
            public void onSuccess(Object model) {
                GiftListModel m = (GiftListModel) model;
                KKYUtil.log("加载礼物结果：" + m.getResponseStr());
                KKYApp.getInstance().GIFTS.clear();
                KKYApp.getInstance().GIFTS_PAGES.clear();
                KKYApp.getInstance().GIFTS.addAll(m.getData());
                List<Gift> gifts = m.getData();
                int size = gifts.size();
                int pageSize = 8;//每页8个
                int count = size / pageSize;//count总页数
                if (size % 8 != 0) {
                    count = count + 1;
                }
                for (int i = 0; i < count; i++) {
                    KKYApp.getInstance().GIFTS_PAGES.add(gifts.subList(i * 8, Math.min(size, (i * 8) + 8)));
                }
                KKYUtil.log("Main主界面加载礼物列表任务OK!");
            }

            @Override
            public void onErr(String errMsg) {
                mainView.showTopMsg(errMsg);
            }
        });
    }

    /**
     * 加载系统默认通知
     */
    private void loadSystemMsg(){
        OKHttpParam param=OKHttpParam.builder();
        OKHttp.post(HttpConfig.API_GET_SYSTEM_DEFAULT_MSG,param.jsonParam(),TAG,new OKHttpUIHandler(SystemMsgModel.class) {
            @Override
            public void onSuccess(Object model) {
                SystemMsgModel m=(SystemMsgModel)model;
                SYSTEM_MSG.clear();
                SYSTEM_MSG.addAll(m.getData());
                //SystemDefaultMsg msg=new SystemDefaultMsg();
                //msg.setContent("提倡绿色直播，提倡绿色直播，提倡绿色直播，提倡绿色直播，提倡绿色直播，提倡绿色直播，提倡绿色直播，");
                //SYSTEM_MSG.add(msg);
                KKYUtil.log("加载默认系统公告："+SYSTEM_MSG.size());
            }
            @Override
            public void onErr(String errMsg) {
                mainView.showTopMsg(errMsg);
            }
        });
    }

    /**
     * 处理语言切换事件
     */
    @Subscribe
    public void onSwitchLanguage(OnLanguageEvent event) {
        configLanguage();
        OKHttp.parseErrMsg(this);
        KKYApp.initLoveStates(this);
        liveFrag=null;
        if(handler!=null){
            handler.post(new Runnable() {
                @Override
                public void run() {
                    if(indexMenuTitle!=null){
                        indexMenuTitle.setText(R.string.ui_live_title);
                    }
                    if(userMenuTitle!=null){
                        userMenuTitle.setText(R.string.ui_user_title);
                    }
                    if(userFrag!=null){
                        userFrag.onSwitchLanguage();
                    }
                }
            });
        }
    }

}
